<template>
  <view class="container">
    <view class="">
      <view class="project-switcher" v-if="projectshow">
        <picker
          class="project-picker"
          @change="switchProject"
          :value="projectIndex"
          :range="projectList"
          range-key="title"
        >
          <view class="picker">
            当前项目：{{ currentProjectTitle }}
            <view class="picker-icon">▼</view>
          </view>
        </picker>
      </view>

      <!-- 附件列表 -->
      <view
        class="attachment-list"
        v-if="currentAttachments && currentAttachments.length > 0"
      >
        <view
          class="attachment-item"
          v-for="(item, index) in currentAttachments"
          :key="index"
        >
          <view class="attachment-name">{{ item.name }}</view>
          <view class="download-btn" @click="downloadFile(item.url)">下载</view>
        </view>
      </view>
      <view v-else class="no-attachment"> 暂无附件 </view>
    </view>
  </view>
</template>

<script>
import { qingdaoProject } from "../../utils/getDate.js";

export default {
  data() {
    return {
      projectshow: true,
      trainingScore: 0,
      teacherScore: 0,
      feedbackInfo: "",
      projectId: "", // 从options获取的id
      projectList: [], // 项目列表
      currentProjectId: "", // 当前项目ID
      currentProjectTitle: "请选择项目", // 当前项目名称
      projectIndex: 0, // 当前项目索引
      selectedProjectId: "", // 选中的项目ID
      allProjectsData: [], // 所有项目数据
      currentAttachments: [], // 当前项目的附件列表
    };
  },
  onLoad(options) {
    this.userId = uni.getStorageSync("userinfo").id;

    if (options.id) {
      // 如果有传入的项目ID，直接使用
      this.projectId = options.id;
      this.currentProjectId = options.id;
      // 如果有传入项目名称，也一并设置
      if (options.name) {
        this.currentProjectTitle = decodeURIComponent(options.name);
      }
      this.projectshow = false;
      // 直接获取项目详情
      this.getProjectDetail(this.currentProjectId);
    } else {
      // 没有传入ID，获取项目列表
      this.getProjectList();
    }
  },
  methods: {
    // 切换项目
    switchProject(e) {
      const index = e.detail.value;
      this.projectIndex = index;
      this.currentProjectId = this.projectList[index].projectId;
      this.currentProjectTitle = this.projectList[index].title;
      this.selectedProjectId = this.currentProjectId;

      // 切换项目后更新附件列表
      this.updateAttachments();
    },

    // 获取项目列表
    async getProjectList() {
      try {
        const res = await qingdaoProject({
          userId: this.userId,
        });
        if (res.state === "ok") {
          this.allProjectsData = res.data; // 保存所有项目数据
          this.projectList = res.data.map((item) => ({
            title: item.title,
            projectId: item.id,
          }));

          // 默认选中第一个项目
          if (this.projectList.length > 0) {
            this.currentProjectId = this.projectList[0].projectId;
            this.currentProjectTitle = this.projectList[0].title;
            this.selectedProjectId = this.currentProjectId;
            this.projectIndex = 0;

            // 更新附件列表
            this.updateAttachments();
          }
        }
      } catch (error) {
        console.error("获取项目列表失败:", error);
        uni.showToast({
          title: "获取项目列表失败",
          icon: "none",
        });
      }
    },

    // 获取项目详情
    async getProjectDetail(projectId) {
      try {
        const res = await qingdaoProject({
          userId: this.userId,
        });
        if (res.state === "ok") {
          this.allProjectsData = res.data;
          const project = res.data.find((item) => item.id == projectId);
          if (project) {
            this.currentProjectTitle = project.title;
            this.parseAttachments(project.attachments);
          }
        }
      } catch (error) {
        console.error("获取项目详情失败:", error);
        uni.showToast({
          title: "获取项目详情失败",
          icon: "none",
        });
      }
    },

    // 更新附件列表
    updateAttachments() {
      const currentProject = this.allProjectsData.find(
        (item) => item.id == this.currentProjectId
      );
      if (currentProject && currentProject.attachments) {
        this.parseAttachments(currentProject.attachments);
      } else {
        this.currentAttachments = [];
      }
    },

    // 解析附件数据
    parseAttachments(attachmentsStr) {
      try {
        if (attachmentsStr) {
          const attachments = JSON.parse(attachmentsStr);
          this.currentAttachments = Array.isArray(attachments)
            ? attachments
            : [];
        } else {
          this.currentAttachments = [];
        }
      } catch (e) {
        console.error("解析附件失败:", e);
        this.currentAttachments = [];
      }
    },

    // 下载文件
    // 增强版下载方法
    async downloadFile(url, fileName) {
      try {
        uni.showLoading({
          title: "正在下载...",
          mask: true,
        });

        // 检查网络状态
        const networkType = await this.getNetworkType();
        if (networkType !== "wifi") {
          const { confirm } = await uni.showModal({
            title: "流量提醒",
            content: "当前非WiFi网络，下载将消耗流量，是否继续？",
            confirmText: "继续下载",
            cancelText: "取消",
          });
          if (!confirm) {
            uni.hideLoading();
            return;
          }
        }

        // 开始下载
        const downloadTask = uni.downloadFile({
          url: url,
          success: async (downloadRes) => {
            if (downloadRes.statusCode === 200) {
              // 保存文件
              try {
                const saveRes = await uni.saveFile({
                  tempFilePath: downloadRes.tempFilePath,
                });

                uni.hideLoading();
                uni.showToast({
                  title: "下载成功",
                  icon: "success",
                  duration: 2000,
                });

                // 在iOS上可以尝试打开文件
                if (uni.getSystemInfoSync().platform === "ios") {
                  uni.openDocument({
                    filePath: saveRes.savedFilePath,
                    showMenu: true, // 显示右上角菜单，允许转发、收藏等
                    success: () => console.log("打开文档成功"),
                    fail: (err) => console.log("打开文档失败", err),
                  });
                }
              } catch (saveErr) {
                this.handleDownloadError(saveErr, "保存文件失败");
              }
            } else {
              this.handleDownloadError(
                null,
                `下载失败，状态码: ${downloadRes.statusCode}`
              );
            }
          },
          fail: (downloadErr) => {
            this.handleDownloadError(downloadErr, "下载失败");
          },
        });

        // 监听下载进度
        downloadTask.onProgressUpdate((res) => {
          console.log("下载进度", res.progress);
          // 可以在这里更新UI显示下载进度
        });
      } catch (err) {
        this.handleDownloadError(err, "下载过程中出错");
      }
    },

    // 获取网络类型
    getNetworkType() {
      return new Promise((resolve, reject) => {
        uni.getNetworkType({
          success: (res) => resolve(res.networkType),
          fail: (err) => reject(err),
        });
      });
    },

    // 统一处理下载错误
    handleDownloadError(err, defaultMsg) {
      uni.hideLoading();
      console.error("下载错误:", err);

      let errMsg = defaultMsg;
      if (err && err.errMsg) {
        if (err.errMsg.includes("invalid url")) {
          errMsg = "下载地址无效";
        } else if (err.errMsg.includes("域名不在安全列表中")) {
          errMsg = "下载域名未配置，请联系管理员";
        } else {
          errMsg = err.errMsg;
        }
      }

      uni.showToast({
        title: errMsg,
        icon: "none",
        duration: 3000,
      });
    },
  },
};
</script>

<style scoped>
/* 项目选择器样式 */
.project-switcher {
  margin: 30rpx 0;
}

.project-picker {
  background: #fff;
  border-radius: 20rpx;
  padding: 20rpx 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  font-size: 28rpx;
  color: #4b5563;
}

.picker {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.picker-icon {
  font-size: 24rpx;
  color: #9ca3af;
  margin-left: 20rpx;
}

/* 附件列表样式 */
.attachment-list {
  margin-top: 30rpx;
  padding: 20rpx;
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.attachment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.attachment-item:last-child {
  border-bottom: none;
}

.attachment-name {
  font-size: 28rpx;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 20rpx;
}

.download-btn {
  padding: 10rpx 20rpx;
  background: #007aff;
  color: #fff;
  border-radius: 10rpx;
  font-size: 24rpx;
}

.no-attachment {
  margin-top: 30rpx;
  text-align: center;
  color: #999;
  font-size: 28rpx;
  padding: 20rpx;
}
</style>
